#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <pthread.h>
#include <string>

using namespace std;

// 打印线程名称和 tid
void printTid(const char* name, const pthread_t& tid) {
    printf("%s, threadId = %x\n",name, tid);
}


void* startRoutine(void* args) {
    // pthread_detach(pthread_self());  // 进行线程的分离
    const char* name = static_cast<const char*> (args);
    int cnt = 5;
    while (true) {
        cout << name << " running ..." << endl;
        printTid(name, pthread_self());
        sleep(1);
        if (!(cnt --)) {
            break;
        }
    }

    cout << "线程退出了" << endl;
    int* p = new int(10);
    // return (void*) 111;
    return (void*) p;
}


int main() {
    pthread_t tid;

    // tid 也就是线程id
    int pt_ret = pthread_create(&tid, nullptr, startRoutine, (void*) "shit");
    // 线程终止
    // pthread_cancel(tid);
    cout << "cancel success" << endl;

    // 获取这个线程的执行结果 / 返回值
    void* retval = nullptr;  // void* -> 64位 -> 8byte -> 有空间
    pthread_join(tid, &retval);
    cout << "main join success" << endl;
    cout << "retval: " << *((int*)retval) << endl;

    delete (int*)retval; // 转回 int* 再回收
    sleep(10);

    // 让当前进程等待 tid 线程
    pthread_join(tid, nullptr); 
    while (true) {
        printTid("main", pthread_self());
        sleep(1);
    }

}